package cn.harry.component.security.service;

import cn.harry.common.exception.ApiException;
import cn.harry.common.utils.BeanUtils;
import cn.harry.common.utils.SysUserDetails;
import cn.harry.modular.sys.mapper.SysUserMapper;
import cn.harry.modular.sys.domain.SysUser;
import cn.harry.modular.sys.enums.CacheConstants;
import cn.harry.modular.sys.enums.StatusEnums;
import cn.harry.modular.sys.exception.enums.SysExceptionEnum;
import cn.harry.modular.sys.service.SysMenuService;
import cn.harry.modular.sys.service.SysUserRoleService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * ClassName: UserDetailsServiceImpl Description:
 *
 * @author honghh Date 2020/04/13 11:01 Copyright (C) www.tech-harry.cn
 */
@RequiredArgsConstructor
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	private final SysUserMapper sysUserDao;

	private final SysMenuService sysMenuService;

	private final SysUserRoleService sysUserRoleService;

	private final CacheManager cacheManager;

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {

		Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
		if (cache != null && cache.get(username) != null) {
			return (SysUserDetails) cache.get(username).get();
		}
		// 获取登录用户信息
		SysUser user = sysUserDao.selectOne(
				Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));

		// 用户不存在
		if (BeanUtils.isNull(user)) {
			throw new ApiException(SysExceptionEnum.USER_NOT_EXIST);
		}

		// 用户停用
		if (StatusEnums.DISABLE.getKey().equals(user.getStatus())) {
			throw new ApiException(SysExceptionEnum.USER_DISABLED);
		}

		// 获取用户菜单权限标识
		List<String> permissions = sysMenuService.getMenuPermission(user.getId());

		// 获取用户角色
		List<String> roles = sysUserRoleService.listRoleKeyByUserId(user.getId());

		SysUserDetails userDetails = new SysUserDetails(user, permissions, roles);

		if (cache != null) {
			cache.put(username, userDetails);
		}
		return userDetails;
	}

}
